package com.keafmd.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPatch;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.keafmd.entity.EbSysArea;
import lombok.var;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenji
 * @date 2022/1/13 12:44
 */
@Aspect
@Component
public class SelfZhuJieAspect {

    @Pointcut("@annotation(SelfZhuJie)")
    public void selfZhuJieCut() {
    }

    @Around("selfZhuJieCut()")
    public Object getUserMsgFromRedis(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object arg = args[0];
        if (ObjectUtils.isNotEmpty(arg)&& arg instanceof EbSysArea){
            EbSysArea arg1 = (EbSysArea) arg;
            arg1.setAreaId("6666666");
        }
        return joinPoint.proceed(args);
    }

    @Async
    @AfterReturning(pointcut = "selfZhuJieCut()",returning = "obj")
    public void afterCut(JoinPoint joinPoint, Object obj){
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录下请求内容
        Map<String, Object> map = new HashMap<>();
        map.put("URL" , request.getRequestURL().toString());
        map.put("HTTP_METHOD" , request.getMethod());
        map.put("IP" , request.getRemoteAddr());
        map.put("PATH" ,request.getServletPath());
        map.put("METHOD", request.getMethod());
        map.put("CLASS_METHOD" , joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        map.put("ARGS" , Arrays.toString(joinPoint.getArgs()));
        Object arg = joinPoint.getArgs()[0];
        EbSysArea arg1 = (EbSysArea) arg;
        System.out.println(arg1);
        EbSysArea obj1 = (EbSysArea) obj;
        System.out.println(obj1);
        map.put("RESULT",obj1);
        System.out.println(map);
    }

    @Async
    @AfterThrowing(pointcut = "@annotation(selfZhuJie)", throwing = "e")
    public void recordLog(JoinPoint joinPoint, SelfZhuJie selfZhuJie, Exception e) {
        // 异常情况记录日志
        System.out.println(e);
        System.out.println(e);
    }



}
